package com.example.demo.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

public class GetFansDesc {
    private static Integer ZERO_LV_NUM = 0;

    public static void main(String[] args) throws IOException {
        String authorId = "290526283";
        ArrayList<String> fansIds = new ArrayList<>();

        for (int i = 0; i < 1; i++) {
            URL authorUrl = new URL("https://api.bilibili.com/x/relation/followers?vmid=" + authorId + "&pn=" + i + 1 +"ps=2000");
            StringBuilder builder = getResultString(authorUrl);
            JSONObject jsonObject = JSON.parseObject(builder.toString());
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray list = data.getJSONArray("list");
            for (Object o : list) {
                JSONObject object = JSON.parseObject(o.toString());
                fansIds.add(object.get("mid").toString());
            }
            statZeroLvNum(fansIds);
        }
        System.out.println(ZERO_LV_NUM);
    }

    private static void statZeroLvNum(ArrayList<String> fansIds) throws IOException {
        for (String fansId : fansIds) {
            URL fansUrl = new URL("https://api.bilibili.com/x/space/acc/info?mid=" + fansId + "&jsonp=jsonp");
            StringBuilder resultString = getResultString(fansUrl);
            Object level = JSON.parseObject(resultString.toString()).getJSONObject("data").get("level");
            if ("0".equals(level.toString())) {
                ZERO_LV_NUM++;
            }
        }
    }

    private static StringBuilder getResultString(URL url) throws IOException {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("182.34.32.240", 9999));
        URLConnection urlConnection = url.openConnection(proxy);
        InputStream inputStream = urlConnection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuilder builder = new StringBuilder();
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }
            builder.append(line);
        }
        return builder;
    }
}
